package cn.kvchoi.reactor_simulation;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Dispatcher {

    private final Map<EventType, EventHandler> eventHandlerMap = new HashMap<>();

    private final Selector selector;

    public Dispatcher(Selector selector) {
        this.selector = selector;
    }

    public void registerHandler(EventType eventType, EventHandler handler) {
        eventHandlerMap.put(eventType, handler);
    }

    public void removeHandler(EventType eventType) {
        eventHandlerMap.remove(eventType);
    }

    public void handle() {
        dispatch();
    }

    private void dispatch() {
        while (true) {
            List<Event> events;
//            events = selector.selectNow();
            events = selector.select(100);

            for (Event event : events) {
                EventHandler eventHandler = eventHandlerMap.get(event.type);
                eventHandler.handle(event);
            }
        }
    }
}  